#include"Library.h"
void initList(LibList* libList)
{
	FILE* fi = fopen("书籍信息.txt", "r+b");
	if (fi == NULL)
	{
		fi = fopen("书籍信息.txt", "w+b");
		for (int i = 0; i < 100; i++)
		{
			generateSingleBook(libList);
		}
		libList->bookNum = 100;
		return;
	}
	Book fbook;
	bookNode* head = libList->head;
	fread(fbook.ISBN, MAX_ISBN, 1, fi);
	fread(fbook.name, MAX_BOOK_NAME, 1, fi);
	fread(fbook.auth, MAX_AUTH_NAME, 1, fi);
	fread(&fbook.price, sizeof(float), 1, fi);
	fread(&fbook.inventory, sizeof(int), 1, fi);
	while (!feof(fi))
	{
		bookNode* cur = new bookNode;
		strcpy(cur->data.ISBN, fbook.ISBN);
		strcpy(cur->data.name, fbook.name);
		strcpy(cur->data.auth, fbook.auth);
		cur->data.price = fbook.price;
		cur->data.inventory = fbook.inventory;
		cur->next = NULL;
		if (head == NULL)
		{
			libList->head = cur;
			head = libList->head;
		}
		else
		{
			while (head->next)
			{
				head = head->next;
			}
			head->next = cur;
		}
		fread(fbook.ISBN, MAX_ISBN, 1, fi);
		fread(fbook.name, MAX_BOOK_NAME, 1, fi);
		fread(fbook.auth, MAX_AUTH_NAME, 1, fi);
		fread(&fbook.price, sizeof(float), 1, fi);
		fread(&fbook.inventory, sizeof(int), 1, fi);
	}
	fclose(fi);
}
void generateISBN(char ISBN[]) {
	for (int i = 0; i < 13; i++)
	{
		ISBN[i] = '0' + rand() % 10;
	}
	ISBN[13] = 0;
}
void generateName(char name[]) {
	char vowels[] = "aeiou";
	char consonants[] = "bcdfghjklmnpqrstvwxyz";

	int length = rand() % MAX_BOOK_NAME + 1;
	int startWithVowel = rand() % 2;

	for (int i = 0; i < length; i++) {
		if (i % 2 == startWithVowel) {
			name[i] = vowels[rand() % strlen(vowels)];
		}
		else {
			name[i] = consonants[rand() % strlen(consonants)];
		}
	}
	name[length] = '\0';
}
void generateAuth(char auth[]) {
	char vowels[] = "aeiou";
	char consonants[] = "bcdfghjklmnpqrstvwxyz";

	int length = rand() % MAX_AUTH_NAME + 1;
	int startWithVowel = rand() % 2;

	for (int i = 0; i < length; i++) {
		if (i % 2 == startWithVowel) {
			auth[i] = vowels[rand() % strlen(vowels)];
		}
		else {
			auth[i] = consonants[rand() % strlen(consonants)];
		}
	}
	auth[length] = '\0';
}
float generatePrice() {
	return (float)(rand() % (int)(MAX_PRICE * 100)) / 100.0;
}
void generateSingleBook(LibList* libList)
{
	bookNode* head = libList->head;
	bookNode* add = new bookNode;
	generateISBN(add->data.ISBN);
	generateName(add->data.name);
	generateAuth(add->data.auth);
	add->data.price = generatePrice();
	add->data.inventory = rand() % MAX_BOOKS;
	add->next = NULL;
	if (head == NULL)
	{
		libList->head = add;
	}
	else
	{
		while (head->next)
		{
			head = head->next;
		}
		head->next = add;
	}
}
